#!/usr/bin/python3.7.3
# !coding:utf-8
import requests

'''
生成依赖包
pip freeze > requirements.txt
安装依赖包
pip install -r requirement.txt
'''

BASE_URL = 'https://192.168.2.98'
API_KEY = "eb13230e-3b8c-4588-8c82-872043d95df9"
headers = {"Content-Type": "application/x-www-form-urlencoded; charset=UTF-8", 'Connection': 'keep-alive'}


def url(api_url):
    import re
    s = ('?' if (re.search('\?+', api_url) == None) else '&')
    return BASE_URL + api_url + s + "key=" + API_KEY


def post(api_url, params):
    # 不允许重定向，如果允许重定向添加数据成功后重定向到编辑页面就无法获取到302状态码和headers的Localtion参数
    r = requests.post(url(api_url), data=params, json=params, headers=headers, verify=False, allow_redirects=False)
    # res = json.loads(r.text)
    return r


def get(api_url):
    r = requests.get(url(api_url), headers=headers, verify=False)
    # print(r.status_code)  # 打印状态码
    # print(r.headers)      #打印返回的报头（头部）
    # res = json.loads(r.text)
    # print(r.content)  # 查看返回结果的文本形式（body部分）
    return r


def url2json(url, skip_empty=True):
    params = {}
    for p in url.split("&"):
        kv = p.split("=")
        if (skip_empty == True and (kv[1] == '' or kv[1] == None)):
            continue
        params[kv[0]] = kv[1]
    return params


def spider(html):
    from bs4 import BeautifulSoup
    soup = BeautifulSoup(html, 'html.parser')
    return soup


if __name__ == '__main__':
    import re

    print(url('/app/extensions/extension_edit.php?id=1&cd=3'))
    pass
